<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04控制图层不透明度</title>
  <link rel="stylesheet" href="../ol/ol.css">
  <style>
    html, body {
      margin: 0;
    }
    #map {
      width: 400px;
      height: 400px;
    }
  </style>
</head>
<body>

<label for="checkboxEl">不透明度</label>
<input
  id="rangeEl"
  type="range"
  checked="true"
  min="0"
  max="1"
  step="0.01"
  value="0.5"
/>

<div id="opacityValue">不透明度: 0.5</div>

<div id="map"></div>

<script src="../ol/ol.js"></script>
<script>

  const map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM(),
        opacity: 0.5
      })
    ],
    view: new ol.View({
      center: [0, 0],
      zoom: 2
    })
  })

  let rangeEl = document.getElementById('rangeEl')
  rangeEl.addEventListener('change', function() {

    let layers = map.getLayers() // 获取图层组
    let osmLayer = layers.item(0) // 因为只有一个图层，所以直接 item(0) 即可拿到

    osmLayer.setOpacity(parseFloat(this.value)) // 设置图层不透明度

    opacityValue.innerHTML = `不透明度: ${osmLayer.getOpacity()}` // 获取图层不透明度，并展示在页面中
  })
</script>
</body>
</html>